package me.pcqpcq.android.aclean;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import me.pcqpcq.android.Constant;
import me.pcqpcq.android.adapter.SimpleCleanAdapter;
import me.pcqpcq.android.data.CleanListData;
import me.pcqpcq.android.msg.MessageCentre;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

/**
 * 展示一个列表，用于选择目录，并把路径作为结果返回
 * <p>前一个页面需传递key为filepath的初始路径</p>
 * @author pcqpcq
 *
 */
public class PickDirActivity extends Activity {

	private SimpleCleanAdapter curPathAdapter, curFilesAdapter;
	private ArrayList<HashMap<String, Object>> curPathList = new ArrayList<HashMap<String, Object>>();
	private ArrayList<HashMap<String, Object>> curFilesList = new ArrayList<HashMap<String, Object>>();
	private Intent data;
	private String curPath = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_pickdir);

		data = getIntent();
		if (data != null) {
			String filePath = data.getStringExtra("filepath");
			if (filePath != null) {
				buildPathList(filePath);
				buildFilesList(filePath);
			}
		} else
			Log.e("TAG", "PickDirActivity getIntent Fail!");
	}

	/**
	 * 点击列表时
	 * @param v
	 */
	public void onPick(View v) {
		switch (v.getId()) {
		case R.id.pickdir_btn_confirm:
			data.putExtra("curpath", curPath);
			setResult(Constant.RESULT_CODE_PICK_DIR, data);
			onBackPressed();
			break;

		case R.id.pickdir_btn_cancle:
			onBackPressed();
			break;

		default:
			onBackPressed();
			break;
		}
	}

	/**
	 * 构建当前路径下的目录结构
	 * @param filePath 当前路径
	 */
	private void buildPathList(String filePath) {
		File file = new File(filePath);
		if (file.exists() && file.canRead()) {
			curPath = filePath;
			curPathList = getCurPathList(filePath);
			curPathAdapter =
					new SimpleCleanAdapter(PickDirActivity.this, curPathList, R.layout.listview_curpath_item,
							new String[] { "filename" }, new int[] { R.id.pickdir_curpath_item_textview });
			ListView curPathView = (ListView) findViewById(R.id.pickdir_list_curpath);
			curPathView.setAdapter(curPathAdapter);
			curPathView.setOnItemClickListener(new PathItemClickListener());
		} else
			MessageCentre.showShortToast(getString(R.string.toast_no_readable));
	}

	/**
	 * 构建当前路径下的文件列表
	 * @param filePath 当前路径
	 */
	private void buildFilesList(String filePath) {
		File file = new File(filePath);
		if (file.exists() && file.canRead()) {
			curPath = filePath;
			curFilesList = getCurFilesList(file);
			curFilesAdapter =
					new SimpleCleanAdapter(PickDirActivity.this, curFilesList, R.layout.listview_item,
							new String[] { "icon", "filename" }, new int[] { R.id.listview_icon, R.id.listview_textview });
			ListView curFilesView = (ListView) findViewById(R.id.pickdir_list_curfiles);
			curFilesView.setAdapter(curFilesAdapter);
			curFilesView.setOnItemClickListener(new FilesItemClickListener());
		} else
			MessageCentre.showShortToast(getString(R.string.toast_no_readable));
	}

	private ArrayList<HashMap<String, Object>> getCurPathList(String filePath) {
		ArrayList<HashMap<String, Object>> arrList = new ArrayList<HashMap<String, Object>>();

		// 添加根目录
		HashMap<String, Object> rootMap = new HashMap<String, Object>();
		rootMap.put("filename", "/");
		rootMap.put("file", new File("/"));
		arrList.add(rootMap);

		String[] pathArray = filePath.split("/");
		StringBuffer strBuffer = new StringBuffer();
		for (int i = 1; i < pathArray.length; i++) {
			int j = 0;
			while (j <= i) {
				if (j > 0)
					strBuffer.append("/");
				strBuffer.append(pathArray[j]);
				j++;
			}
			String filePathStr = strBuffer.toString();
			HashMap<String, Object> hashMap = new HashMap<String, Object>();
			hashMap.put("filename", new File(filePathStr).getName());
			hashMap.put("file", new File(filePathStr));
			arrList.add(hashMap);
			strBuffer.delete(0, strBuffer.length());
		}
		return arrList;
	}

	private ArrayList<HashMap<String, Object>> getCurFilesList(File filePath) {
		ArrayList<HashMap<String, Object>> arrList = new ArrayList<HashMap<String, Object>>();
		List<File> fileList = CleanListData.getListAsc(filePath);
		if (fileList != null) {
			for (File file : fileList) {
				HashMap<String, Object> hashMap = new HashMap<String, Object>();
				if (file.isFile())
					hashMap.put("icon", R.drawable.ic_file);
				else 
					hashMap.put("icon", R.drawable.ic_folder);
				hashMap.put("filename", (String) file.getName());
				hashMap.put("file", file);
				arrList.add(hashMap);
			}
		} else
			MessageCentre.showShortToast(getString(R.string.toast_no_readable));
		return arrList;
	}

	/**
	 * 目录树点击监听器
	 * @author pcqpcq
	 *
	 */
	protected class PathItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
				if (curPathList != null) {
					String filePath = ((File) (curPathList.get(position).get("file"))).getAbsolutePath();
					if (!filePath.equals(curPath)) {
						buildPathList(filePath);
						buildFilesList(filePath);
					}
				}
			} else
				MessageCentre.showShortToast(getString(R.string.toast_no_sdcard));
		}

	}

	/**
	 * 文件列表点击监听器
	 * @author pcqpcq
	 *
	 */
	protected class FilesItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
				if (curFilesList != null) {
					String filePath = ((File) (curFilesList.get(position).get("file"))).getAbsolutePath();
					File file = new File(filePath);
					if (file.isDirectory()) {
						buildPathList(filePath);
						buildFilesList(filePath);
					} else
						Toast.makeText(PickDirActivity.this, R.string.toast_no_dir, Toast.LENGTH_SHORT).show();
				}
			} else
				MessageCentre.showShortToast(getString(R.string.toast_no_sdcard));
		}

	}

}
